package com.blb.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 自定义eureka客户端
 */
@Component
public class MyEurekaClient {

    public static final String COMMAND_REGISTRY = "registry";
    public static final String COMMAND_RENEW = "renew";
    public static final String COMMAND_SEARCH = "search";

    @Autowired
    private MyEurekaConfig config;

    /**
     * 连接服务器发送命令并返回结果
     * @param command
     * @return
     */
    public String connect(String command){
        try (Socket socket = new Socket(config.getServerIp(),config.getServerPort());
             ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())){
            outputStream.writeUTF(command);
            outputStream.flush();
            String result = inputStream.readUTF();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送注册命令
     * @return
     */
    public String register(){
        String command = COMMAND_REGISTRY + " " + config.getAppName() + " " + config.getClientIp() + " " + config.getClientPort();
        return connect(command);
    }

    /**
     * 定时发送心跳包，更新服务信息
     */
    public void renew(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            String command = COMMAND_RENEW+ " " + config.getAppName() + " " + config.getClientIp() + " " + config.getClientPort();
            String res = connect(command);
            System.out.println(res);
        },5,10, TimeUnit.SECONDS);
    }

    /**
     * 根据服务名称搜索地址
     * @param serviceName
     * @return
     */
    public String search(String serviceName){
        String command = COMMAND_SEARCH + " " + serviceName;
        return connect(command);
    }

    /**
     * 发送get http请求
     * @param serviceName
     * @param path
     * @return
     */
    public String get(String serviceName,String path){
        String addr = search(serviceName);
        try {
            URL url = new URL("http://" + addr + path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            if(conn.getResponseCode() == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String result = reader.readLine();
                reader.close();
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
